package com.adams.custom.page.core.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;

import com.adams.access.db.bean.DicColumn;
import com.adams.access.db.bean.DicDatabase;
import com.adams.access.db.bean.DicElement;
import com.adams.access.db.bean.DicTable;
import com.adams.core.exception.BusinessException;
import com.adams.custom.page.core.dao.impl.DicColumnDaoImpl;
import com.adams.custom.page.core.dao.impl.DicDatabaseDaoImpl;
import com.adams.custom.page.core.dao.impl.DicElementDaoImpl;
import com.adams.custom.page.core.dao.impl.DicTableDaoImpl;
import com.adams.custom.page.core.dao.impl.DynamicDBDaoImpl;
import com.adams.custom.page.core.dto.DicColumnDto;
import com.adams.custom.page.core.service.DicTableService;
import com.adams.custom.page.util.DataOperateMessageUtil;
import com.adams.custom.page.util.ViewUtil;
import com.adams.utils.SpringBeanFactoryUtil;

/**
 * 
 * File Name : DicTableServiceImpl.java
 * 
 * @Description : 数据字典服务实现类
 * @author 904370
 */
public class DicTableServiceImpl implements DicTableService
{

	Logger logger = Logger.getLogger(DicTableServiceImpl.class.getName());

	private static String TABLE_ALIAS = "tbalias_";
	/**
	 * Description : 数据库定义数据访问实现类 Author : 904370
	 */
	private DicDatabaseDaoImpl dicDatabaseDaoImpl;

	/**
	 * Description : 表定义数据访问实现类 Author : 904370
	 */
	private DicTableDaoImpl dicTableDaoImpl;

	/**
	 * Description : 表字段定义数据访问实现类 Author : 904370
	 */
	private DicColumnDaoImpl dicColumnDaoImpl;

	/**
	 * Description : 数据项定义数据访问实现类 Author : 904370
	 */
	private DicElementDaoImpl dicElementDaoImpl;

	/**
	 * Description : 动态数据访问实现类 Author : 904370
	 */
	private DynamicDBDaoImpl dynamicDBDaoImpl;

	public void setDicDatabaseDaoImpl(DicDatabaseDaoImpl dicDatabaseDaoImpl)
	{
		this.dicDatabaseDaoImpl = dicDatabaseDaoImpl;
	}

	/**
	 * @param dicTableDaoImpl
	 *            the dicTableDaoImpl to set
	 */
	public void setDicTableDaoImpl(DicTableDaoImpl dicTableDaoImpl)
	{
		this.dicTableDaoImpl = dicTableDaoImpl;
	}

	/**
	 * @param dicColumnDaoImpl
	 *            the dicColumnDaoImpl to set
	 */
	public void setDicColumnDaoImpl(DicColumnDaoImpl dicColumnDaoImpl)
	{
		this.dicColumnDaoImpl = dicColumnDaoImpl;
	}

	/**
	 * @param dicElementDaoImpl
	 *            the dicElementDaoImpl to set
	 */
	public void setDicElementDaoImpl(DicElementDaoImpl dicElementDaoImpl)
	{
		this.dicElementDaoImpl = dicElementDaoImpl;
	}

	/**
	 * @param dynamicDBDaoImpl
	 *            the dynamicDBDaoImpl to set
	 */
	public void setDynamicDBDaoImpl(DynamicDBDaoImpl dynamicDBDaoImpl)
	{
		this.dynamicDBDaoImpl = dynamicDBDaoImpl;
	}

	/**
	 * Description : 根据表名得到数据库连接对象
	 * 
	 * @param tablecode
	 * @return
	 * @throws BusinessException
	 * 
	 */
	public String getDatabase(String tablecode) throws BusinessException
	{
		logger.info("getDatabase method run begin.");
		DicTable dicTable = getDicTable(tablecode);
		String databasecode = dicTable.getDatabasecode();
		DicDatabase dicDatabase = dicDatabaseDaoImpl
				.getDicDatabase(databasecode);
		logger.info("getDatabase method run end.");
		return dicDatabase.getDatabasecode();
	}

	/**
	 * Description : 根据目标表名及关系字段 得到关联表是否在同一个数据库中
	 * 
	 * @param tablecode
	 * @param columncodes
	 * @throws BusinessException
	 * 
	 */
	public boolean isSameDatabase(String tablecode, List<String> columncodes)
			throws BusinessException
	{
		logger.info("isSameDatabase method run begin.");
		boolean result = true;

		DicColumn dicColunm = null;
		DicTable dicTable = null;
		String database = getDatabase(tablecode);
		String finalTableCode = tablecode;
		int len = columncodes.size();
		for (int i = 0; i < len; i++)
		{
			String tempdatabase = getDatabase(finalTableCode);
			if (!tempdatabase.equals(database))
			{
				result = false;
			}
			String colunmcode = columncodes.get(i);
			dicColunm = getDicColumn(finalTableCode, colunmcode);
			if (len > 1 && i == len - 2)
			{
				String last = columncodes.get(i + 1);
				if (null != dicColunm
						&& !ViewUtil.isNuLLStr(dicColunm.getEnumeratemap())
						&& DicColumn.ENUMERATE_VALUE_TAG.equals(last))
				{
					break;
				}
			}

			dicTable = getDicTable(finalTableCode);
			String keycolumn = dicTable.getKeycolumns();
			if (colunmcode.equals(keycolumn))
			{
				finalTableCode = dicColunm.getTargettable();
			} else
			{
				finalTableCode = dicColunm.getSourcetable();
			}

		}
		logger.info("isSameDatabase method run end.");
		return result;
	}

	/**
	 * Description : 判断列表中的表是否在同一个数据库中
	 * 
	 * @param tablecode
	 * @param columncodes
	 * @throws BusinessException
	 * 
	 */
	public boolean isSameDatabase(List<String> tablecodes)
			throws BusinessException
	{
		logger.info("isSameDatabase method run begin.");
		if (null == tablecodes || tablecodes.size() <= 1)
		{
			return true;
		}
		String firsttable = tablecodes.get(0);
		String firsttabledb = getDatabase(firsttable);
		int len = tablecodes.size();
		for (int i = 1; i < len; i++)
		{
			String table = tablecodes.get(i);
			String db = getDatabase(table);
			if (!firsttabledb.equals(db))
			{
				return false;
			}
		}
		logger.info("isSameDatabase method run end.");
		return true;
	}

	/**
	 * Description : 根据表名得到数据库连接对象
	 * 
	 * @param tablecode
	 * @return
	 * @throws BusinessException
	 * 
	 */
	private String getDatabaseBeanName(String tablecode)
			throws BusinessException
	{
		DicTable dicTable = getDicTable(tablecode);
		String databasecode = dicTable.getDatabasecode();
		DicDatabase dicDatabase = dicDatabaseDaoImpl
				.getDicDatabase(databasecode);
		String beanname = dicDatabase.getBeanname();
		Object result = SpringBeanFactoryUtil.getBean(beanname);
		if (null == result)
		{
			logger.error("服务配置错误，没对应" + dicDatabase.getDatabasename()
					+ "数据库连接资源!");
			throw new BusinessException("database.connectionbean.exception");
		}
		return beanname;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @seecom.adams.custom.page.core.service.impl.DicTableService#
	 * findValueByTableCodeAndColumncodes(java.lang.String, java.util.List,
	 * java.util.Map)
	 */
	@SuppressWarnings("unchecked")
	public Object findValueByTableCodeAndColumncodes(String tableCode,
			List<String> columncodes, Map inputMap) throws BusinessException
	{
		logger.info("findValueByTableCodeAndColumncodes method run begin.");
		Object result = null;
		if (null == columncodes || columncodes.size() == 0)
		{
			return result;
		}

		List<DicColumn> refDicColumns = new ArrayList<DicColumn>();
		DicColumn firstDicColumn = this.getDicColumn(tableCode, columncodes
				.get(0));

		boolean isEnumerate = false;
		DicColumn enumerateDicColumn = null;

		String targetTablecode = tableCode;
		String targetColumncode = "";

		int columncodesLen = columncodes.size();
		for (int i = 0; i < columncodesLen; i++)
		{
			String columncode = columncodes.get(i);
			targetColumncode = columncode;
			DicColumn dicColumn = getDicColumn(targetTablecode, columncode);
			List<Map> enumerate = dicColumn.getEnumerate();

			refDicColumns.add(dicColumn);
			if (i == columncodesLen - 1)
			{
				continue;
			}
			if (enumerate.size() > 0)
			{
				if (i == columncodesLen - 2
						&& DicColumn.ENUMERATE_VALUE_TAG.equals(columncodes
								.get(columncodesLen - 1)))
				{
					isEnumerate = true;
					enumerateDicColumn = dicColumn;
					targetColumncode = dicColumn.getDicColumnPK()
							.getColumncode();
					break;
				} else
				{
					throw new BusinessException("table.parse.exception");
				}
			} else
			{
				String sourcetable = dicColumn.getSourcetable();
				if (ViewUtil.isNuLLStr(sourcetable))
				{
					throw new BusinessException("table.parse.exception");
				}
				targetTablecode = sourcetable;
			}
		}

		Collections.reverse(refDicColumns);

		Object value = null;

		// 如果是本层的枚举,如果传入参数中也有相应的值时,直接转译,不发查询
		if (isEnumerate && refDicColumns.size() == 1)
		{
			if (inputMap.containsKey(firstDicColumn.getDicColumnPK()
					.getColumncode()))
			{
				value = inputMap.get(firstDicColumn.getDicColumnPK()
						.getColumncode());
				if (null != value && !"".equals(value.toString()))
				{
					result = enumerateDicColumn.getEnumerateValue(value
							.toString());
					return result;
				}
			}
		}

		// 产生查询sql
		String sql = buildFindValueByTableCodeAndColumncodesSql(tableCode,
				inputMap, refDicColumns, targetTablecode, targetColumncode);

		// 组装要显示的数据信息
		List<DicColumn> findColumns = new ArrayList<DicColumn>();
		findColumns.addAll(findDBDicColumnsByTablecode(targetTablecode));
		// findColumns.add(this.getDicColumn(targetTablecode,
		// targetColumncode));
		List<Map> datas = findData(targetTablecode, DicColumnDto
				.create(findColumns), sql, 0, 0);

		DicColumn targetDicColumn = this.getDicColumn(targetTablecode,
				targetColumncode);
		// 数据转换
		if (datas.size() == 0)
		{
			value = transformByDicColumn(targetDicColumn, null);
		} else
		{
			Map valuemap = datas.get(0);
			value = transformByDicColumn(targetDicColumn, valuemap
					.get(targetColumncode));
		}

		if (isEnumerate)
		{
			result = enumerateDicColumn.getEnumerateValue(value.toString());
		} else
		{
			result = value;
		}
		logger.info("findValueByTableCodeAndColumncodes method run end.");
		return result;
	}

	private List<List<DicColumn>> getRefDicColumnsByDatabase(
			List<DicColumn> refDicColumns) throws BusinessException
	{
		List<List<DicColumn>> dicColumnsByDB = new ArrayList<List<DicColumn>>();
		DicColumn firstDicColumn = refDicColumns.get(0);
		String tablecode = firstDicColumn.getDicColumnPK().getTablecode();
		String database = getDatabase(tablecode);
		List<DicColumn> dicColumns = new ArrayList<DicColumn>();
		for (DicColumn refDicColumn : refDicColumns)
		{
			tablecode = refDicColumn.getDicColumnPK().getTablecode();
			String tempdatabase = getDatabase(tablecode);
			if (database.equals(tempdatabase))
			{
				dicColumns.add(refDicColumn);
			} else
			{
				dicColumnsByDB.add(dicColumns);
				dicColumns = new ArrayList<DicColumn>();
				dicColumns.add(refDicColumn);
				database = tempdatabase;
			}
		}
		if (dicColumns.size() > 0)
		{
			dicColumnsByDB.add(dicColumns);
		}
		return dicColumnsByDB;
	}

	@SuppressWarnings("unchecked")
	private String buildFindValueByTableCodeAndColumncodesSql(String tableCode,
			Map inputMap, List<DicColumn> refDicColumns,
			String targetTablecode, String targetColumncode)
			throws BusinessException
	{
		List<List<DicColumn>> refDicColumnsByDB = getRefDicColumnsByDatabase(refDicColumns);

		int dblen = refDicColumnsByDB.size();
		StringBuilder sql = new StringBuilder();
		StringBuilder conditionsSql = new StringBuilder();
		for (int i = dblen - 1; i >= 0; i--)
		{
			sql.delete(0, sql.length());
			List<DicColumn> dicColumns = refDicColumnsByDB.get(i);
			int columnlen = dicColumns.size();

			DicColumn firstColumn = dicColumns.get(0);
			String firstColumncode = firstColumn.getDicColumnPK()
					.getColumncode();
			String selectTablecode = firstColumn.getDicColumnPK()
					.getTablecode();
			DicTable selectTable = getDicTable(selectTablecode);
			if (selectTable.isCompositeKey())
			{
				logger.error("配置错误，" + selectTablecode + "表不是单主键表！");
				throw new BusinessException("table.config.exception");
			}
			int dbtnum = 0;
			if (i == 0)
			{
				sql.append("select ");
				List<DicColumn> selectDicColumns = findDBDicColumnsByTablecode(targetTablecode);
				int selectLen = selectDicColumns.size();
				for (int j = 0; j < selectLen; j++)
				{
					DicColumn selectDicColumn = selectDicColumns.get(j);
					String selectcolumncode = selectDicColumn.getDicColumnPK()
							.getColumncode();
					sql.append(TABLE_ALIAS + dbtnum);
					sql.append(".");
					sql.append(selectcolumncode);
					sql.append(" column_" + j);
					sql.append(",");
				}
				if (selectLen > 0)
				{
					sql.deleteCharAt(sql.length() - 1);
				}
				sql.append(" from ");
				sql.append(getTableNameSqlByTablecode(targetTablecode));
				sql.append(" " + TABLE_ALIAS + dbtnum + " ");
				sql.append("where 1=1 ");
			} else
			{
				sql.append("select ");
				sql.append(TABLE_ALIAS + dbtnum);
				sql.append(".");
				sql.append(firstColumncode);
				sql.append(" from ");
				sql.append(getTableNameSqlByTablecode(selectTablecode));
				sql.append(" " + TABLE_ALIAS + dbtnum + " ");
				sql.append("where 1=1 ");
			}

			for (int j = 0; j < columnlen; j++)
			{
				if (columnlen > 1 && j > 0)
				{
					sql.append("and ");
					DicColumn refDicColumn = refDicColumns.get(j);
					DicColumn refSrcDicColumn = getSinglePkColumnByTablecode(refDicColumn
							.getSourcetable());
					DicColumn refTargetDicColumn = refDicColumn;
					sql.append(TABLE_ALIAS + dbtnum);
					sql.append(".");
					sql
							.append(refSrcDicColumn.getDicColumnPK()
									.getColumncode());
					sql.append(" = (select ");
					dbtnum++;
					sql.append(TABLE_ALIAS + dbtnum);
					sql.append(".");
					sql.append(refTargetDicColumn.getDicColumnPK()
							.getColumncode());
					sql.append(" from ");
					sql.append(getTableNameSqlByTablecode(refDicColumn
							.getDicColumnPK().getTablecode()));

					sql.append(" " + TABLE_ALIAS + dbtnum + " ");
					sql.append("where 1=1 ");
				}
				// 最后一条
				if (j == columnlen - 1)
				{
					if (i == dblen - 1)
					{
						// 如果是分组中的最后一组,使用传入参数作查询过滤条件
						DicTable srcDicTable = getDicTable(tableCode);
						List<String> keycolumns = srcDicTable
								.getKeycolumnlist();
						String keyWhereSql = getWhereSqlByKeycolumn(tableCode,
								keycolumns, TABLE_ALIAS + dbtnum, inputMap);
						if (!ViewUtil.isNuLLStr(keyWhereSql))
						{
							sql.append("and ");
							sql.append(keyWhereSql + " ");
						}
					}
					if (conditionsSql.length() > 0)
					{
						sql.append("and ");
						sql.append(" " + TABLE_ALIAS + dbtnum + " ");
						sql.append(".");
						sql.append(conditionsSql + " ");
					}
					for (int k = 1; k < columnlen; k++)
					{
						sql.append(")");
					}
					// 是分组中的第一组时,返回
					if (i == 0)
					{
						return sql.toString();
					}
					// 不是分组中的第一组时,使用sql进行查询得到中间结果集 提供给下一个分组使用
					String datatype = firstColumn.getDatatype();
					List<DicColumnDto> dicColumnDtos = new ArrayList<DicColumnDto>();
					DicColumnDto dicColumnDto = new DicColumnDto(firstColumn);
					dicColumnDtos.add(dicColumnDto);
					List<Map> idList = findData(selectTablecode, dicColumnDtos,
							sql.toString(), 0, 0);

					String sourcetablecode = firstColumn.getSourcetable();
					DicTable sourcetable = getDicTable(sourcetablecode);
					if (sourcetable.isCompositeKey())
					{
						logger.error("配置错误，" + sourcetablecode + "表不是单主键表！");
						throw new BusinessException("table.config.exception");
					}

					conditionsSql.delete(0, conditionsSql.length());
					if (idList.size() > 0)
					{
						conditionsSql.append(sourcetable.getKeycolumns());
						conditionsSql.append("=");
						Map id = idList.get(0);
						String value = id.get(firstColumncode).toString();
						if (DicColumn.DATATYPE_NUM.equals(datatype))
						{
							conditionsSql.append(value);
						} else
						{
							conditionsSql.append("'");
							conditionsSql.append(value);
							conditionsSql.append("' ");
						}
					}
				}
			}
		}
		return sql.toString();
	}

	/**
	 * Description : 根据表编码得到表名sql
	 * 
	 * @param tablecode
	 * @return
	 * @throws BusinessException
	 * 
	 */
	public String getTableNameSqlByTablecode(String tablecode)
			throws BusinessException
	{
		logger.info("getTableNameSqlByTablecode method run begin.");
		StringBuilder result = new StringBuilder();
		DicTable lastDicTable = this.getDicTable(tablecode);
		String tabletype = lastDicTable.getTabletype();
		if (DicTable.TABLETYPE_DBT.equals(tabletype))
		{
			result.append(tablecode);
		} else if (DicTable.TABLETYPE_DBV.equals(tabletype))
		{
			result.append("(");
			result.append(lastDicTable.getViewsql());
			result.append(")");
		} else
		{
			logger.error(tablecode + "表配置出错，表定义解析出错！");
			throw new BusinessException("table.parse.exception");
		}
		logger.info("getTableNameSqlByTablecode method run end.");
		return result.toString();
	}

	/**
	 * Description : 得到表关系sql
	 * 
	 * @param srcDicColumn
	 * @param srcAlias
	 * @param targetColumn
	 * @param targetAlias
	 * @return
	 * @throws BusinessException
	 * 
	 */
	private String getTableRefSql(DicColumn srcDicColumn, String srcAlias,
			DicColumn targetColumn, String targetAlias)
			throws BusinessException
	{
		StringBuilder result = new StringBuilder();
		String srcTablecode = srcDicColumn.getDicColumnPK().getTablecode();
		String srcColumncode = srcDicColumn.getDicColumnPK().getColumncode();
		if (!ViewUtil.isNuLLStr(srcAlias))
		{
			result.append(srcAlias);
		} else
		{
			result.append(srcTablecode);
		}
		result.append(".");
		result.append(srcColumncode);
		result.append("=");

		String targetTablecode = targetColumn.getDicColumnPK().getTablecode();
		String targetColumncode = targetColumn.getDicColumnPK().getColumncode();
		if (!ViewUtil.isNuLLStr(targetAlias))
		{
			result.append(targetAlias);
		} else
		{
			result.append(targetTablecode);
		}
		result.append(".");
		result.append(targetColumncode);
		return result.toString();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @seecom.adams.custom.page.core.service.impl.DicTableService#
	 * getSinglePkColumnByTablecode(java.lang.String)
	 */
	public DicColumn getSinglePkColumnByTablecode(String tablecode)
			throws BusinessException
	{
		logger.info("getSinglePkColumnByTablecode method run begin.");
		DicColumn result = null;
		DicTable dicTable = this.getDicTable(tablecode);
		String keycolumns = dicTable.getKeycolumns();
		if (ViewUtil.isNuLLStr(keycolumns))
		{
			logger.error(tablecode + "表没有配置主键!");
			throw new BusinessException("table.no.has.keycolumn.exception");
		}
		if (keycolumns.indexOf(DicTable.COLUMNS_SEQ) > -1)
		{
			logger.error(tablecode + "表配置的不是单一主键!");
			throw new BusinessException("table.no.only.keycolumn.exception");
		}
		result = getDicColumn(tablecode, keycolumns);
		logger.info("getSinglePkColumnByTablecode method run end.");
		return result;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @seecom.adams.custom.page.core.service.impl.DicTableService#
	 * findAllDicTable()
	 */
	public List<DicTable> findAllDicTable()
	{
		logger.info("findAllDicTable method run begin.");
		List<DicTable> result = dicTableDaoImpl.findAll();
		logger.info("findAllDicTable method run end.");
		return result;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.adams.custom.page.core.service.impl.DicTableService#getDicTable
	 * (java.lang.String)
	 */
	public DicTable getDicTable(String tablecode) throws BusinessException
	{
		logger.info("getDicTable method run begin.");
		DicTable result = dicTableDaoImpl.getDicTable(tablecode);
		logger.info("getDicTable method run end.");
		return result;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @seecom.adams.custom.page.core.service.impl.DicTableService#
	 * findDicColumnsByTablecode(java.lang.String)
	 */
	public List<DicColumn> findDicColumnsByTablecode(String tablecode)
	{
		logger.info("findDicColumnsByTablecode method run begin.");
		List<DicColumn> result = dicColumnDaoImpl.findByTablecode(tablecode);
		logger.info("findDicColumnsByTablecode method run end.");
		return result;
	}

	/**
	 * Description : 根据表编码查询冗余字段定义
	 * 
	 * @param tablecode
	 * @return
	 * 
	 */
	public List<DicColumn> findRddcolumnByTablecode(String tablecode)
	{
		logger.info("findRddcolumnByTablecode method run begin.");
		List<DicColumn> result = dicColumnDaoImpl
				.findRddcolumnByTablecode(tablecode);
		logger.info("findRddcolumnByTablecode method run end.");
		return result;
	}

	/**
	 * Description : 根据来源数据表编码查询冗余字段定义
	 * 
	 * @param tablecode
	 * @return
	 * 
	 */
	public List<DicColumn> findByRddsourcetablecode(String rddsourcetable)
	{
		logger.info("findRddcolumnByTablecode method run begin.");
		List<DicColumn> result = dicColumnDaoImpl
				.findByRddsourcetablecode(rddsourcetable);
		logger.info("findRddcolumnByTablecode method run end.");
		return result;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.adams.custom.page.core.service.impl.DicTableService#getDicColumn
	 * (java.lang.String, java.lang.String)
	 */
	public DicColumn getDicColumn(String tablecode, String columncode)
			throws BusinessException
	{
		logger.info("getDicColumn method run begin.");
		DicColumn result = dicColumnDaoImpl.get(tablecode, columncode);
		logger.info("getDicColumn method run end.");
		return result;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.adams.custom.page.core.service.DicTableService#getFinalDicColumn
	 * (java.lang.String, java.util.List)
	 */
	public DicColumn getFinalDicColumn(String tablecode,
			List<String> colunmcodes) throws BusinessException
	{
		logger.info("getFinalDicColumn method run begin.");
		DicColumn result = null;
		DicTable dicTable = null;
		String finalTableCode = tablecode;
		int len = colunmcodes.size();
		int lastsecondly = len - 2;
		for (int i = 0; i < len; i++)
		{
			String colunmcode = colunmcodes.get(i);
			result = getDicColumn(finalTableCode, colunmcode);
			if (len > 1 && i == lastsecondly)
			{
				String last = colunmcodes.get(i + 1);
				if (null != result
						&& !ViewUtil.isNuLLStr(result.getEnumeratemap())
						&& DicColumn.ENUMERATE_TAG_SET.contains(last))
				{
					break;
				}
			}

			dicTable = getDicTable(finalTableCode);
			String keycolumn = dicTable.getKeycolumns();
			if (colunmcode.equals(keycolumn))
			{
				finalTableCode = result.getTargettable();
			} else
			{
				finalTableCode = result.getSourcetable();
			}

		}
		logger.info("getFinalDicColumn method run end.");
		return result;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.adams.custom.page.core.service.impl.DicTableService#findDicElement
	 * (java.lang.String)
	 */
	public DicElement findDicElement(String elementcode)
			throws BusinessException
	{
		logger.info("findDicElement method run begin.");
		DicElement result = dicElementDaoImpl.getDicElement(elementcode);
		logger.info("findDicElement method run end.");
		return result;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @seecom.adams.custom.page.core.service.impl.DicTableService#
	 * getElementsByElementCode(java.lang.String, java.util.Set)
	 */
	@SuppressWarnings("unchecked")
	public List<Map> getElementsByElementCode(String elementcode,
			Set<String> columns) throws BusinessException
	{
		logger.info("getElementsByElementCode method run begin.");
		List<Map> result = new ArrayList<Map>();
		DicElement dicElement = dicElementDaoImpl.getDicElement(elementcode);
		String tablecode = dicElement.getTablecode();
		String condition = dicElement.getCondition();
		DicTable dicTable = getDicTable(tablecode);
		String alias = TABLE_ALIAS + 0;
		List<DicColumn> dicColumns = findDicColumnsByTablecode(tablecode);
		for (DicColumn dicColumn : dicColumns)
		{
			String columncode = dicColumn.getDicColumnPK().getColumncode();
			String key = "{@" + columncode + "}";
			String value = alias + "." + columncode;
			condition = strReplace(condition, key, value);
		}

		List<DicColumn> needColumns = new ArrayList<DicColumn>();
		if (null != columns && columns.size() > 0)
		{
			for (String columncode : columns)
			{
				DicColumn dicColumn = getDicColumn(tablecode, columncode);
				if (null != dicColumn)
				{
					needColumns.add(dicColumn);
				}
			}
		} else
		{
			needColumns = dicColumns;
		}

		String sql = buildSearchSql(dicTable, needColumns, alias, condition,
				null);
		result = findData(tablecode, DicColumnDto.create(needColumns), sql, 0,
				0);
		logger.info("getElementsByElementCode method run end.");
		return result;
	}

	/**
	 * 字符串替换函数
	 * 
	 * @param sAll
	 *            String 原来的字符串
	 * @param older
	 *            String 要替换掉的字符串
	 * @param newer
	 *            String 新的字符串
	 * @return String 替换后的结果
	 */
	public static String strReplace(String sAll, String sOld, String sNew)
	{
		int iT = 0;
		String sF = null, sH = null;
		// 如果新串中包括旧串,不让替多只让替少
		if (sNew.indexOf(sOld) != -1)
			return sAll;

		if (sAll == null || sOld == null || sNew == null)
			return sAll;
		iT = sAll.indexOf(sOld);
		while (iT != -1)
		{
			sF = sAll.substring(0, iT);
			sH = sAll.substring(iT + sOld.length());
			sAll = sF + sNew + sH;
			iT = sAll.indexOf(sOld);
		}
		return sAll;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.adams.custom.page.core.service.impl.DicTableService#buildSearchSql
	 * (com.adams.access.db.bean.DicTable, java.util.List,
	 * java.lang.String, java.lang.String)
	 */
	public String buildSearchSql(DicTable dicTable, List<DicColumn> dicColumns,
			String dbalias, String whereSql, List<DicColumn> orderDicColumns)
			throws BusinessException
	{
		logger.info("buildSearchSql method run begin.");
		StringBuilder sql = new StringBuilder();
		sql.append("select ");

		int length = dicColumns.size();
		for (int i = 0; i < length; i++)
		{
			DicColumn dicColumn = dicColumns.get(i);
			sql.append(dbalias);
			sql.append(".").append(dicColumn.getDicColumnPK().getColumncode());
			sql.append(",");
		}
		sql.deleteCharAt(sql.length() - 1);
		sql.append(" from ");
		sql.append(getTableNameSqlByTablecode(dicTable.getTablecode()));
		sql.append(" " + dbalias);
		sql.append(" ");
		if (!ViewUtil.isNuLLStr(whereSql))
		{
			sql.append(" where ");
			sql.append(whereSql);
			sql.append(" ");
		}
		sql.append("order by ");
		if (null != orderDicColumns && orderDicColumns.size() > 0)
		{
			for (DicColumn orderDicColumn : orderDicColumns)
			{
				sql.append(orderDicColumn.getDicColumnPK().getColumncode());
				sql.append(",");
			}
			sql.deleteCharAt(sql.length() - 1);
		} else
		{
			String keycolumns = dicTable.getKeycolumns();
			if (!ViewUtil.isNuLLStr(keycolumns))
			{
				sql.append(keycolumns);
			}
		}
		sql.append(" ");
		logger.info("buildSearchSql method run end.");
		return sql.toString();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.adams.custom.page.core.service.impl.DicTableService#findData
	 * (com.adams.access.db.bean.DicTable, java.util.List, int, int)
	 */
	@SuppressWarnings("unchecked")
	public List<Map> findData(DicTable dicTable, List<DicColumn> dicColumns,
			int start, int limit) throws BusinessException
	{
		logger.info("findData method run begin.");
		List<Map> result = new ArrayList<Map>();
		if (null == dicTable
				|| (!"0".equals(dicTable.getTabletype()) && !"1"
						.equals(dicTable.getTabletype())))
		{
			return result;
		}
		if (null == dicColumns || dicColumns.size() == 0)
		{
			return result;
		}
		String sql = buildSearchSql(dicTable, dicColumns, TABLE_ALIAS + 0,
				null, null);
		result = findData(dicTable.getTablecode(), DicColumnDto
				.create(dicColumns), sql, start, limit);
		logger.info("findData method run end.");
		return result;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.adams.custom.page.core.service.impl.DicTableService#findAllData
	 * (java.lang.String, java.util.List)
	 */
	@SuppressWarnings("unchecked")
	public List<Map> findAllData(String tablecode, List<DicColumn> dicColumns)
			throws BusinessException
	{
		logger.info("findAllData method run begin.");
		List<Map> result = new ArrayList<Map>();
		DicTable dicTable = getDicTable(tablecode);
		if (null == dicTable
				|| (!"0".equals(dicTable.getTabletype()) && !"1"
						.equals(dicTable.getTabletype())))
		{
			return result;
		}
		if (null == dicColumns || dicColumns.size() == 0)
		{
			return result;
		}
		String sql = buildSearchSql(dicTable, dicColumns, TABLE_ALIAS + 0,
				null, null);
		result = findData(tablecode, DicColumnDto.create(dicColumns), sql, 0, 0);
		logger.info("findAllData method run end.");
		return result;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.adams.custom.page.core.service.impl.DicTableService#getCount
	 * (java.lang.String, java.lang.String, java.lang.String)
	 */
	public int getCount(String tablecode, String dbalias, String whereSql)
			throws BusinessException
	{
		logger.info("getCount method run begin.");
		StringBuilder sql = new StringBuilder();
		sql.append("select count(*) from ");
		DicTable dicTable = getDicTable(tablecode);
		sql.append(getTableNameSqlByTablecode(dicTable.getTablecode()));
		sql.append(" " + dbalias);
		sql.append(" ");
		if (!ViewUtil.isNuLLStr(whereSql))
		{
			sql.append(" where ");
			sql.append(whereSql);
			sql.append(" ");
		}
		String connectionBeanName = getDatabaseBeanName(tablecode);
		int result = dynamicDBDaoImpl.getCount(connectionBeanName, sql
				.toString());
		logger.info("getCount method run end.");
		return result;
	}

	public int getCount(String tablecode, String sql) throws BusinessException
	{
		logger.info("getCount method run begin.");
		String connectionBeanName = getDatabaseBeanName(tablecode);
		int result = dynamicDBDaoImpl.getCount(connectionBeanName, sql
				.toString());
		logger.info("getCount method run end.");
		return result;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.adams.custom.page.core.service.impl.DicTableService#findData
	 * (java.util.List, java.lang.String, int, int)
	 */
	@SuppressWarnings("unchecked")
	public List<Map> findData(String tablecode,
			List<DicColumnDto> dicColumnDtos, String sql, int start, int limit)
			throws BusinessException
	{
		logger.info("findData method run begin.");
		List<Map> result = new ArrayList<Map>();
		String connectionBeanName = getDatabaseBeanName(tablecode);
		List rows = dynamicDBDaoImpl.findData(connectionBeanName, sql, start,
				limit);
		int columnsLen = dicColumnDtos.size();
		if (null != rows && rows.size() > 0)
		{
			for (int i = 0; i < rows.size(); i++)
			{
				Map record = new HashMap();
				if (columnsLen > 1)
				{
					Object[] columns = (Object[]) rows.get(i);
					for (int j = 0; j < columnsLen; j++)
					{
						DicColumnDto dicColumnDto = dicColumnDtos.get(j);
						DicColumn dicColumn = dicColumnDto.getDicColumn();
						Object value = transformByDicColumn(dicColumn,
								columns[j]);
						record.put(dicColumnDto.getAttributecode(), value);
					}
				} else
				{
					DicColumnDto dicColumnDto = dicColumnDtos.get(0);
					DicColumn dicColumn = dicColumnDto.getDicColumn();
					Object columns = rows.get(i);
					Object value = transformByDicColumn(dicColumn, columns);
					record.put(dicColumnDto.getAttributecode(), value);
				}
				result.add(record);
			}
		}
		logger.info("findData method run end.");
		return result;
	}

	private Object transformByDicColumn(DicColumn dicColumn, Object value)
			throws BusinessException
	{
		String datatype = dicColumn.getDatatype();
		if ("D".equals(datatype))
		{
			if (value == null)
			{
				return null;
			}
			if (value instanceof java.util.Date)
			{
				return ViewUtil.Date2Str((java.util.Date) value);
			} else
			{
				return value.toString();
			}

		} else if ("T".equals(datatype))
		{
			if (value == null)
			{
				return null;
			}
			if (value instanceof java.util.Date)
			{
				return ViewUtil.Time2Str((java.util.Date) value);
			} else
			{
				return value.toString();
			}
		} else if ("B".equals(datatype))
		{
			return value;
		} else if ("N".equals(datatype))
		{
			String valueStr = "";
			if (null == value || ViewUtil.isNuLLStr(value.toString()))
			{
				return valueStr;
			}
			valueStr = "0";
			int datadecimals = dicColumn.getDatadecimals();
			if (null != value && ViewUtil.isNum(value.toString()))
			{
				valueStr = String.valueOf(value);
			}
			BigDecimal result = ViewUtil.round(valueStr, datadecimals);
			return result.toString();
		} else if ("L".equals(datatype))
		{
			if (null != value && ViewUtil.isBoolean(value.toString()))
			{
				if ("1".equals(value.toString())
						|| "true".equals(value.toString()))
				{
					return Boolean.TRUE.toString();
				} else
				{
					return Boolean.FALSE.toString();
				}

			} else
			{
				return "";
			}
		} else
		{
			if (value == null)
			{
				return "";
			}
			return value.toString();
		}
	}

	/**
	 * Description : 版本字段处理
	 * 
	 * 
	 */
	@SuppressWarnings("unchecked")
	private void updateVersioncolumnValue(DicTable dicTable, Map newdata,
			Map olddata) throws BusinessException
	{
		String tablecode = dicTable.getTablecode();
		String versioncolumn = dicTable.getVersioncolumn();
		if (ViewUtil.isNuLLStr(versioncolumn))
		{
			return;
		}
		DicColumn versionDicColumn = getDicColumn(tablecode, versioncolumn);
		if (null == versionDicColumn)
		{
			return;
		}
		// 版本控制字段检查
		if (null != olddata
				&& !ViewUtil.isNuLLValueInMap(olddata, versioncolumn))
		{
			String oldVersion = olddata.get(versioncolumn).toString();
			if (null == newdata
					|| ViewUtil.isNuLLValueInMap(newdata, versioncolumn))
			{
				logger.error("输入参数出错,需要使用版本控制字段!");
				throw new BusinessException("data.input.exception");
			}
			String newVersion = newdata.get(versioncolumn).toString();
			if (!oldVersion.equals(newVersion))
			{
				logger.error("版本字段值不相等,数据已经被操作过!");
				throw new BusinessException("data.input.isold.exception");
			}
		}

		String dataType = versionDicColumn.getDatatype();
		if (DicColumn.DATATYPE_DATE.equals(dataType)
				|| DicColumn.DATATYPE_TIME.equals(dataType))
		{
			// 修改时间
			Date now = new Date();
			newdata.put(versioncolumn, ViewUtil.Time2Str(now));
		} else if (DicColumn.DATATYPE_LOGIC.equals(dataType))
		{
			logger.error(tablecode + "表的版本控制字段设置为" + versionDicColumn
					+ "字段，但此字段的数据类型为逻辑型!不能作为版本控制字段.");
			throw new BusinessException("table.config.exception");
		} else
		{
			if (!ViewUtil.isNuLLValueInMap(newdata, versioncolumn))
			{
				String value = newdata.get(versioncolumn).toString();
				if (ViewUtil.isInt(value))
				{
					newdata.put(versioncolumn, Integer.valueOf(value) + 1);
					return;
				}
			}
			newdata.put(versioncolumn, "0");
		}
	}

	/**
	 * Description : 排序字段处理
	 * 
	 * 
	 */
	@SuppressWarnings("unchecked")
	private void updateOrderValue(DicTable dicTable, List<Map> inputMaps)
			throws BusinessException
	{
		String tablecode = dicTable.getTablecode();
		String ordercolumns = dicTable.getOrdercolumn();
		if (ViewUtil.isNuLLStr(ordercolumns))
		{
			return;
		}
		String[] ordercolumnArray = ordercolumns.split(",");
		for (int i = 0; i < ordercolumnArray.length; i++)
		{
			String ordercolumn = ordercolumnArray[i];
			if (ViewUtil.isNuLLStr(ordercolumn))
			{
				return;
			}
			DicColumn orderDicColumn = getDicColumn(tablecode, ordercolumn);
			if (null == orderDicColumn)
			{
				return;
			}

			StringBuilder sql = new StringBuilder();
			sql.append("select max(");
			sql.append(ordercolumn).append(") ");
			sql.append("from ").append(tablecode);
			String connectionBeanName = getDatabaseBeanName(tablecode);
			int maxordernum = dynamicDBDaoImpl.getCount(connectionBeanName, sql
					.toString()) + 1;
			for (Map inputMap : inputMaps)
			{
				String value = "";
				if (inputMap.containsKey(ordercolumn))
				{
					if (null != inputMap.get(ordercolumn))
					{
						value = inputMap.get(ordercolumn).toString();
					}
				}
				if (!ViewUtil.isNuLLStr(value) && ViewUtil.isNum(value))
				{
					continue;
				}
				inputMap.put(ordercolumn, maxordernum + "");
				maxordernum++;
			}
		}
	}

	/**
	 * Description : 检查输入数据是否符合唯一约束
	 * 
	 * 
	 */
	@SuppressWarnings("unchecked")
	private void checkDataByUniqueconstraints(DicTable dicTable,
			List<Map> inputMaps, boolean isnewdata) throws BusinessException
	{
		String tablecode = dicTable.getTablecode();
		DicColumn dicColumn = null;
		if (!ViewUtil.isNuLLStr(dicTable.getUniqueconstraints()))
		{
			List<Set<String>> uniqueconstraints = dicTable
					.getUniqueconstraint();
			// 检查本输入数据中互相是否有违反唯一约束
			for (Set<String> columns : uniqueconstraints)
			{
				Set<String> keySet = new HashSet<String>();
				for (Map inputMap : inputMaps)
				{
					StringBuilder keySB = new StringBuilder();
					for (String column : columns)
					{
						keySB.append(column);
						keySB.append("=");
						if (!ViewUtil.isNuLLValueInMap(inputMap, column))
						{
							keySB.append(inputMap.get(column).toString());
						}
						keySB.append(" ");
					}
					String key = keySB.toString();
					if (keySet.contains(key))
					{
						StringBuilder msg = new StringBuilder("输入入数据中存在相同记录,");
						for (String column : columns)
						{
							dicColumn = getDicColumn(tablecode, column);
							msg.append("字段 ");
							msg.append(dicColumn.getColumnname());
						}
						msg.append(" 复合数值必须唯一.");
						logger.error(msg.toString());
						throw new BusinessException(
								"inputdata.has.record.exception");
					}
					keySet.add(key);
				}
			}
			// 检查输入数据与数据库数据是否有违返唯一约束
			for (Set<String> columns : uniqueconstraints)
			{
				// 组装检查查询的sql
				StringBuilder ckeckSql = new StringBuilder("select count(");
				List<String> keycolumns = dicTable.getKeycolumnlist();
				if (keycolumns.size() > 0)
				{
					for (String keycolumn : keycolumns)
					{
						ckeckSql.append("t.");
						ckeckSql.append(keycolumn);
						ckeckSql.append(",");
					}
					ckeckSql.deleteCharAt(ckeckSql.length() - 1);
				} else
				{
					ckeckSql.append("*");
				}
				ckeckSql.append(") from ");
				ckeckSql.append(tablecode);
				ckeckSql.append(" t where ");
				for (Map inputMap : inputMaps)
				{
					ckeckSql.append("(");
					for (String column : columns)
					{
						if (!ViewUtil.isNuLLValueInMap(inputMap, column))
						{
							dicColumn = this.getDicColumn(tablecode, column);
							String columnEqValueSql = this
									.buildColumnEqValueSqlByDicColumn("t",
											column, "=", dicColumn, inputMap);
							ckeckSql.append(columnEqValueSql);
						} else
						{
							ckeckSql.append(column);
							ckeckSql.append(" is null");
						}
						ckeckSql.append(" and ");
					}
					if (!isnewdata)
					{
						for (String keycolumn : keycolumns)
						{
							dicColumn = this.getDicColumn(tablecode, keycolumn);
							String columnNeqValueSql = this
									.buildColumnEqValueSqlByDicColumn("t",
											keycolumn, "!=", dicColumn,
											inputMap);
							ckeckSql.append(columnNeqValueSql);
							ckeckSql.append(" and ");
						}
					}
					ckeckSql.delete(ckeckSql.length() - 4, ckeckSql.length());
					ckeckSql.append(")");
					ckeckSql.append(" or ");
				}
				if (inputMaps.size() > 0)
				{
					ckeckSql.delete(ckeckSql.length() - 3, ckeckSql.length());
				}
				// 执行sql 如果有记录就表示已存在违反了唯一约束
				String connectionBeanName = getDatabaseBeanName(tablecode);
				int count = dynamicDBDaoImpl.getCount(connectionBeanName,
						ckeckSql.toString());
				if (count > 0)
				{
					StringBuilder msg = new StringBuilder("输入数据在数据库已存在相同记录!");
					for (String column : columns)
					{
						dicColumn = getDicColumn(tablecode, column);
						msg.append("字段 ");
						msg.append(dicColumn.getColumnname());
					}
					msg.append(" 复合数值必须唯一.");
					logger.error(msg.toString());
					throw new BusinessException("data.has.record.exception");
				}
			}
		}
	}

	/**
	 * Description : 主键字段处理
	 * 
	 * 
	 */
	@SuppressWarnings("unchecked")
	private void dealKeycolumn(DicTable dicTable, List<Map> inputMaps,
			NumColumn numColumn) throws BusinessException
	{
		boolean hasNumId = numColumn.isHasNumId();
		String numIdColumncode = numColumn.getNumIdColumncode();
		boolean incrementColumnHasValue = false;
		String tablecode = dicTable.getTablecode();
		List<String> keycolumns = dicTable.getKeycolumnlist();
		if (keycolumns.size() > 0)
		{
			for (Map inputMap : inputMaps)
			{
				for (String keycolumn : keycolumns)
				{
					DicColumn keyDicColumn = this.getDicColumn(tablecode,
							keycolumn);
					String idcreatetype = keyDicColumn.getIdcreatetype();
					String value = "";
					if (!ViewUtil.isNuLLValueInMap(inputMap, keycolumn))
					{
						value = inputMap.get(keycolumn).toString();
					}

					if (DicColumn.IDCREATETYPE_INCREMENT.equals(idcreatetype))
					{
						if (ViewUtil.isNum(value) && Integer.valueOf(value) > 0)
						{
							incrementColumnHasValue = true;
							continue;
						}
						if (hasNumId && !numIdColumncode.equals(keycolumn))
						{
							logger.error(tablecode + "表配置错误，自增主键只允许有一个！");
							throw new BusinessException(
									"table.has.one.increase.column.exception");

						}
						hasNumId = true;
						numIdColumncode = keycolumn;
					} else if (DicColumn.IDCREATETYPE_UUID.equals(idcreatetype))
					{
						if (!ViewUtil.isNuLLStr(value))
						{
							continue;
						}
						inputMap.put(keycolumn, ViewUtil.createUuid());
					} else
					{

					}
				}
			}
		}
		// 如果有自增字段，并且此字段中输入数据中有空的情况下，输入的数据此字段的值处理清空
		if (hasNumId && incrementColumnHasValue)
		{
			for (Map inputMap : inputMaps)
			{
				inputMap.remove(numIdColumncode);
			}
		}
		numColumn.setHasNumId(hasNumId);
		numColumn.setNumIdColumncode(numIdColumncode);
	}

	/**
	 * 
	 * File Name : 用于记录自增长主键
	 * 
	 * @Description : <Detail Description for Class >
	 * @author 904370 张汉辉
	 */
	class NumColumn
	{
		private boolean hasNumId = false;
		private String numIdColumncode = "";

		public boolean isHasNumId()
		{
			return hasNumId;
		}

		public void setHasNumId(boolean hasNumId)
		{
			this.hasNumId = hasNumId;
		}

		public String getNumIdColumncode()
		{
			return numIdColumncode;
		}

		public void setNumIdColumncode(String numIdColumncode)
		{
			this.numIdColumncode = numIdColumncode;
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.adams.custom.page.core.service.DicTableService#saveDatas(java
	 * .lang.String, java.util.List)
	 */
	@SuppressWarnings("unchecked")
	public List<Map> saveDatas(String tablecode, List<Map> inputMaps)
			throws BusinessException
	{
		logger.info("saveDatas method run begin.");
		DicTable dicTable = dicTableDaoImpl.getDicTable(tablecode);
		String tabletype = dicTable.getTabletype();
		if (!DicTable.TABLETYPE_DBT.equals(tabletype))
		{
			logger.error(tablecode + "不是数据库表,数据库表才能进行增加!");
			throw new BusinessException("data.create.not.dbtable.exception");
		}
		// 检查此表下是否有字段
		checkDicTableHasDicColumns(tablecode);
		// 版本字段处理
		for (Map inputMap : inputMaps)
		{
			updateVersioncolumnValue(dicTable, inputMap, null);
		}

		// 排序字段处理
		updateOrderValue(dicTable, inputMaps);
		// 检查输入数据是否符合唯一约束
		checkDataByUniqueconstraints(dicTable, inputMaps, true);
		// 主键处理
		NumColumn numColumn = new NumColumn();
		dealKeycolumn(dicTable, inputMaps, numColumn);
		boolean hasNumId = numColumn.isHasNumId();
		String numIdColumncode = numColumn.getNumIdColumncode();

		List<DicColumn> dicColumns = findDBDicColumnsByTablecode(tablecode);

		StringBuilder insertSql = new StringBuilder("insert into ");
		insertSql.append(tablecode).append(" ");
		insertSql.append("(");
		// 产生要插入的字段
		StringBuilder columnsSql = new StringBuilder();
		for (DicColumn dicColumn : dicColumns)
		{
			String columncode = dicColumn.getDicColumnPK().getColumncode();
			if (hasNumId)
			{
				if (numIdColumncode.equals(columncode))
				{
					continue;
				}
			}
			columnsSql.append(columncode);
			columnsSql.append(",");
		}
		columnsSql.deleteCharAt(columnsSql.length() - 1);
		insertSql.append(columnsSql);
		insertSql.append(") values ");
		// 产生要插入的字段值
		StringBuilder valueSql = new StringBuilder();
		// 修改时间
		Date now = new Date();
		for (Map inputMap : inputMaps)
		{
			valueSql.append("(");
			for (DicColumn dicColumn : dicColumns)
			{
				String columncode = dicColumn.getDicColumnPK().getColumncode();
				if (hasNumId)
				{
					if (numIdColumncode.equals(columncode))
					{
						continue;
					}
				}
				boolean nullable = dicColumn.getNullable();
				String defaultValue = dicColumn.getDefaultValue();

				String value = null;

				if (inputMap.containsKey(columncode))
				{
					value = inputMap.get(columncode).toString();
				}

				String datatype = dicColumn.getDatatype();
				if ("N".equals(datatype))
				{
					if (ViewUtil.isNum(value))
					{
						valueSql.append(value);
					} else
					{
						if (ViewUtil.isNum(defaultValue))
						{
							valueSql.append(defaultValue);
						} else
						{
							if (nullable)
							{
								valueSql.append("null");
							} else
							{
								logger.error(tablecode + "表的" + columncode
										+ "字段不允许为空！");
								throw new BusinessException(
										"column.not.nullable.exception");
							}
						}
					}
				} else if ("L".equals(datatype))
				{
					if (ViewUtil.isBoolean(value))
					{
						valueSql.append(value);
					} else
					{
						if (ViewUtil.isBoolean(defaultValue))
						{
							valueSql.append(defaultValue);
						} else
						{
							if (nullable)
							{
								valueSql.append("null");
							} else
							{
								logger.error(tablecode + "表的" + columncode
										+ "字段不允许为空！");
								throw new BusinessException(
										"column.not.nullable.exception");
							}

						}
					}
				} else if ("D".equals(datatype))
				{
					if (ViewUtil.isDate(value))
					{
						valueSql.append("'" + value + "'");
					} else
					{
						if (ViewUtil.isDate(defaultValue))
						{
							valueSql.append("'" + defaultValue + "'");
						} else
						{
							if (nullable)
							{
								valueSql.append("null");
							} else
							{

								valueSql.append("'" + ViewUtil.Time2Str(now)
										+ "'");
							}
						}
					}
				} else if ("T".equals(datatype))
				{
					if (ViewUtil.isTime(value))
					{
						valueSql.append("'" + value + "'");
					} else
					{
						if (ViewUtil.isTime(defaultValue))
						{
							valueSql.append(defaultValue);
						} else
						{
							if (nullable)
							{
								valueSql.append("null");
							} else
							{
								valueSql.append("'" + ViewUtil.Time2Str(now)
										+ "'");
							}

						}
					}
				} else
				{
					if (!ViewUtil.isNuLLStr(value))
					{
						value = ViewUtil.dealMysqlSpecialChar(value);
						valueSql.append("'" + value + "'");
					} else
					{
						if (!ViewUtil.isNuLLStr(defaultValue))
						{
							valueSql.append("'" + defaultValue + "'");
						} else
						{
							if (nullable)
							{
								valueSql.append("null");
							} else
							{
								logger.error(tablecode + "表的" + columncode
										+ "字段不允许为空！");
								throw new BusinessException(
										"column.not.nullable.exception");
							}
						}
					}
				}
				valueSql.append(",");
			}
			valueSql.deleteCharAt(valueSql.length() - 1);
			valueSql.append("),");
		}
		valueSql.deleteCharAt(valueSql.length() - 1);
		insertSql.append(valueSql);

		String connectionBeanName = getDatabaseBeanName(tablecode);
		if (hasNumId)
		{
			int numId = dynamicDBDaoImpl.insert(connectionBeanName, insertSql
					.toString());
			for (Map inputMap : inputMaps)
			{
				inputMap.put(numIdColumncode, numId);
				numId++;
			}
		} else
		{
			dynamicDBDaoImpl.execute(connectionBeanName, insertSql.toString());
		}

		// 记录修改对象的信息进入缓存消息中
		List<Map<String, String>> cacheMessages = new ArrayList<Map<String, String>>();
		for (Map inputMap : inputMaps)
		{
			Map<String, String> cacheMessage = createCacheMessage(
					DataOperateMessageUtil.CREATE_ACTION_TYPE, tablecode,
					inputMap);
			cacheMessages.add(cacheMessage);
		}
		DataOperateMessageUtil.addDataOperateMessages(cacheMessages);
		logger.info("saveDatas method run end.");
		return inputMaps;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.adams.custom.page.core.service.DicTableService#saveData(java
	 * .lang.String, java.util.Map)
	 */
	@SuppressWarnings("unchecked")
	public Map saveData(String tablecode, Map inputMap)
			throws BusinessException
	{
		List<Map> inputMaps = new ArrayList<Map>();
		inputMaps.add(inputMap);
		inputMaps = saveDatas(tablecode, inputMaps);
		return inputMaps.get(0);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.adams.custom.page.core.service.DicTableService#updateData(
	 * java.lang.String, java.util.Map, java.util.Map)
	 */
	@SuppressWarnings("unchecked")
	public void updateData(String tablecode, Map newdata, Map olddata)
			throws BusinessException
	{
		logger.info("updateData method run begin.");
		DicTable dicTable = dicTableDaoImpl.getDicTable(tablecode);
		String tabletype = dicTable.getTabletype();
		if (!DicTable.TABLETYPE_DBT.equals(tabletype))
		{
			logger.error(tablecode + "表不是数据库表,数据库表才能进行更新操作!");
			throw new BusinessException("data.update.not.dbtable.exception");
		}
		// 关键字段检查
		checkDicTableKeycolumns(tablecode, newdata);
		List<String> keycolumns = dicTable.getKeycolumnlist();

		checkDicTableHasDicColumns(tablecode);
		// 版本控制处理
		String versioncolumn = dicTable.getVersioncolumn();
		if (!ViewUtil.isNuLLStr(versioncolumn))
		{

			updateVersioncolumnValue(dicTable, newdata, olddata);
		}

		// 冗余字段处理
		Set<String> columncodes = newdata.keySet();
		List<DicColumn> rddDicColumns = findByRddsourcetablecode(tablecode);
		for (String columncode : columncodes)
		{
			if (olddata.containsKey(columncode))
			{
				Object newValue = newdata.get(columncode);
				String newValueStr = "";
				Object oldValue = olddata.get(columncode);
				String oldValueStr = "";
				if (null != newValue)
				{
					newValueStr = String.valueOf(newValue);
				}
				if (null != oldValue)
				{
					oldValueStr = String.valueOf(oldValue);
				}
				// 值发生变化时，对其它表使用到此表冗余字段的处理
				if (!newValueStr.equals(oldValueStr))
				{
					// 检查此字段是否在其它表里成为冗余字段
					for (DicColumn rddDicColumn : rddDicColumns)
					{
						String rddsourcecolumn = rddDicColumn
								.getRddsourcecolumn();
						if (columncode.equals(rddsourcecolumn))
						{
							// 同步处理冗余字段
							updateDataByRddDicColumn(rddDicColumn, newdata);
						}
					}
				}
				newdata.put(columncode, newdata.get(columncode));

			}
		}

		// 检查输入数据是否符合唯一约束
		List<Map> inputMaps = new ArrayList<Map>();
		inputMaps.add(newdata);
		checkDataByUniqueconstraints(dicTable, inputMaps, false);

		// 构造更新sql语句
		List<DicColumn> dicColumns = findDBDicColumnsByTablecode(tablecode);
		StringBuilder updateSql = new StringBuilder("update ");
		updateSql.append(tablecode).append(" t ");
		updateSql.append("set ");
		String columnEqValueSql = buildColumnEqValueSqlByDicColumns("t", ",",
				dicColumns, newdata);
		if (ViewUtil.isNuLLStr(columnEqValueSql))
		{
			logger.error("配置或者输入参数错误，没有找到要更新的内容！");
			throw new BusinessException("data.input.dontupdate.exception");
		}
		updateSql.append(columnEqValueSql);
		updateSql.append(" where ");
		String keyWhereSql = getWhereSqlByKeycolumn(tablecode, keycolumns, "t",
				newdata);
		updateSql.append(keyWhereSql);
		String connectionBeanName = getDatabaseBeanName(tablecode);
		dynamicDBDaoImpl.execute(connectionBeanName, updateSql.toString());

		Map<String, String> cacheMessage = createCacheMessage(
				DataOperateMessageUtil.UPDATE_ACTION_TYPE, tablecode, newdata);
		DataOperateMessageUtil.addDataOperateMessage(cacheMessage);

		logger.info("updateData method run end.");
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @seecom.adams.custom.page.core.service.DicTableService#
	 * updateDataByRddDicColumn(com.adams.access.db.bean.DicColumn,
	 * java.util.Map)
	 */
	@SuppressWarnings("unchecked")
	public void updateDataByRddDicColumn(DicColumn rddDicColumn, Map inputMap)
			throws BusinessException
	{
		logger.info("updateDataByRddDicColumn method run begin.");
		String sourceTablecode = rddDicColumn.getRddsourcetable();
		String sourceColumn = rddDicColumn.getRddsourcecolumn();
		String tablecode = rddDicColumn.getDicColumnPK().getTablecode();
		String columncode = rddDicColumn.getDicColumnPK().getColumncode();
		DicTable rddSourceDicTable = getDicTable(sourceTablecode);
		if (rddSourceDicTable.isCompositeKey())
		{
			StringBuilder msg = new StringBuilder();
			msg.append(tablecode);
			msg.append("表的");
			msg.append(columncode);
			msg.append("字段配为冗余字段错误！");
			msg.append("原因:");
			msg.append(rddSourceDicTable);
			msg.append("为复合主键表！");
			logger.error(msg.toString());
			throw new BusinessException("table.config.exception");
		}
		String sourceKeyColumn = rddSourceDicTable.getKeycolumns();
		if (ViewUtil.isNuLLStr(sourceKeyColumn))
		{
			StringBuilder msg = new StringBuilder();
			msg.append(tablecode);
			msg.append("表的");
			msg.append(columncode);
			msg.append("字段配为冗余字段错误！");
			msg.append("原因:");
			msg.append(rddSourceDicTable);
			msg.append("表没有配置主键！");
			logger.error(msg.toString());
			throw new BusinessException("table.config.exception");
		}
		if (!inputMap.containsKey(sourceKeyColumn))
		{
			throw new BusinessException("data.input.donthaskeycolumn.exception");
		}
		if (null == inputMap.get(sourceKeyColumn))
		{
			throw new BusinessException("data.input.donthaskeycolumn.exception");
		}
		String id = inputMap.get(sourceKeyColumn).toString();
		if (ViewUtil.isNuLLStr(id))
		{
			throw new BusinessException("data.input.donthaskeycolumn.exception");
		}
		int dbtnum = 0;
		StringBuilder updateSql = new StringBuilder("update ");
		updateSql.append(tablecode).append(" ");
		updateSql.append(TABLE_ALIAS + dbtnum);
		updateSql.append(" ");
		updateSql.append("set ");
		DicColumn dicColumn = getDicColumn(sourceTablecode, sourceColumn);
		String columnEqValueSql = this.buildColumnEqValueSqlByDicColumn(
				TABLE_ALIAS + dbtnum, columncode, "=", dicColumn, inputMap);
		updateSql.append(columnEqValueSql);
		updateSql.append(" where 1=1 ");

		int updateSqlContinueBeforeLen = updateSql.length();
		StringBuilder selectSql = new StringBuilder("select ");
		DicTable selectDicTable = getDicTable(tablecode);
		List<String> keycolumns = selectDicTable.getKeycolumnlist();
		int keycolumnslen = keycolumns.size();
		List<DicColumnDto> selectDicColumnDtos = new ArrayList<DicColumnDto>();
		if (keycolumnslen == 0)
		{
			List<DicColumn> selectDicColumns = this
					.findDBDicColumnsByTablecode(tablecode);
			int selectDicColumnlen = selectDicColumns.size();
			for (int i = 0; i < selectDicColumnlen; i++)
			{
				DicColumn selectDicColumn = selectDicColumns.get(i);
				selectSql.append(TABLE_ALIAS + dbtnum);
				selectSql.append(".");
				selectSql.append(selectDicColumn.getDicColumnPK()
						.getColumncode());
				selectSql.append(" column_" + i);
				selectSql.append(",");
				DicColumnDto selectDicColumnDto = new DicColumnDto(
						selectDicColumn);
				selectDicColumnDtos.add(selectDicColumnDto);
			}
		} else
		{
			for (int i = 0; i < keycolumnslen; i++)
			{
				String keycolumn = keycolumns.get(i);
				selectSql.append(TABLE_ALIAS + dbtnum);
				selectSql.append(".");
				selectSql.append(keycolumn);
				selectSql.append(" column_" + i);
				selectSql.append(",");
				DicColumn selectDicColumn = getDicColumn(tablecode, keycolumn);
				DicColumnDto selectDicColumnDto = new DicColumnDto(
						selectDicColumn);
				selectDicColumnDtos.add(selectDicColumnDto);
			}
		}
		selectSql.deleteCharAt(selectSql.length() - 1);
		selectSql.append("from ");
		selectSql.append(tablecode).append(" ");
		selectSql.append(TABLE_ALIAS + dbtnum);
		selectSql.append(" where 1=1 ");

		List<String> itemcolumncodes = rddDicColumn.getRddrelcolumns();
		int len = itemcolumncodes.size();
		String associateTableCode = tablecode;
		StringBuilder temp = new StringBuilder();
		for (int i = 0; i < len; i++)
		{
			String itemcolumncode = itemcolumncodes.get(i);
			dicColumn = getDicColumn(associateTableCode, itemcolumncode);

			dbtnum++;
			String sourcetable = dicColumn.getSourcetable();
			associateTableCode = sourcetable;
			if (associateTableCode == null)
			{
				logger.error(associateTableCode + "表" + columncode + "字段的关联表"
						+ associateTableCode + "不存在！");
				throw new BusinessException("table.config.exception");
			}
			DicTable sourceDicTable = getDicTable(sourcetable);
			updateSql.append("and exists(select ");

			updateSql.append(TABLE_ALIAS + dbtnum);
			updateSql.append(".");
			if (sourceDicTable.isCompositeKey())
			{
				logger.error("配置错误，" + sourcetable + "表不是单主键表！");
				throw new BusinessException("table.config.exception");
			}
			updateSql.append(sourceDicTable.getKeycolumns() + " ");
			updateSql.append(" from ");
			updateSql.append(sourcetable);
			updateSql.append(" ");
			updateSql.append(TABLE_ALIAS + dbtnum);
			updateSql.append(" where ");
			updateSql.append(TABLE_ALIAS);
			updateSql.append(dbtnum - 1 + ".");
			updateSql.append(itemcolumncode);
			updateSql.append(" = ");
			updateSql.append(TABLE_ALIAS);
			updateSql.append(dbtnum + ".");
			updateSql.append(sourceDicTable.getKeycolumns() + " ");
			temp.append(")");

			if (sourceTablecode.equals(associateTableCode))
			{
				columnEqValueSql = this.buildColumnEqValueSqlByDicColumn(
						TABLE_ALIAS + dbtnum, itemcolumncode, "=", dicColumn,
						inputMap);
				updateSql.append("and ");
				updateSql.append(columnEqValueSql);
				break;
			}

		}
		updateSql.append(temp);
		String connectionBeanName = getDatabaseBeanName(tablecode);
		dynamicDBDaoImpl.execute(connectionBeanName, updateSql.toString());

		// 记录修改对象的信息进入缓存消息中
		selectSql.append(updateSql.substring(updateSqlContinueBeforeLen,
				updateSql.length()));

		List<Map> changeDatas = this.findData(tablecode, selectDicColumnDtos,
				selectSql.toString(), 0, 0);
		for (Map changeData : changeDatas)
		{
			Map<String, String> cacheMessage = createCacheMessage(
					DataOperateMessageUtil.UPDATE_ACTION_TYPE, tablecode,
					changeData);
			DataOperateMessageUtil.addDataOperateMessage(cacheMessage);
		}

		logger.info("updateDataByRddDicColumn method run end.");
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.adams.custom.page.core.service.impl.DicTableService#deleteData
	 * (java.lang.String, java.util.List)
	 */
	@SuppressWarnings("unchecked")
	public void deleteData(String tableCode, List<Map> list)
			throws BusinessException
	{
		logger.info("deleteData method run begin.");
		DicTable table = dicTableDaoImpl.getDicTable(tableCode);
		String tabletype = table.getTabletype();
		if (!DicTable.TABLETYPE_DBT.equals(tabletype))
		{
			return;
		}
		boolean deletechilds = table.getDeletechilds();
		List<String> keyColumns = table.getKeycolumnlist();
		if (!table.isCompositeKey())
		{
			DicColumn keycolumn = dicColumnDaoImpl.get(tableCode, table
					.getKeycolumns());
			List<DicColumn> dicColumns = dicColumnDaoImpl
					.findBySourcetablecode(tableCode);
			for (DicColumn dicColumn : dicColumns)
			{
				String childtableCode = dicColumn.getDicColumnPK()
						.getTablecode();
				DicTable childDicTable = getDicTable(childtableCode);
				// 如果子级不是数据库表,或者相关字段不是数据库字段 不处理
				if (null == childDicTable
						|| !DicTable.TABLETYPE_DBT.equals(childDicTable
								.getTabletype())
						|| false == dicColumn.getDbcolumn())
				{
					continue;
				}
				List<DicColumn> childDicColumns = findDicColumnsByTablecode(childtableCode);
				for (Map inputMap : list)
				{
					StringBuilder sql = new StringBuilder();
					sql.append("select ");
					for (DicColumn childDicColumn : childDicColumns)
					{
						sql.append("t1.");
						sql.append(childDicColumn.getDicColumnPK()
								.getColumncode());
						sql.append(",");
					}
					sql.deleteCharAt(sql.length() - 1);
					sql.append(" from ");
					sql.append(childtableCode);
					sql.append(" t1 where exists(select * from ");
					sql.append(tableCode);
					sql.append(" t2 where ");
					String refSql = this.getTableRefSql(dicColumn, "t1",
							keycolumn, "t2");
					sql.append(refSql + " ");
					String keyWhereSql = getWhereSqlByKeycolumn(tableCode,
							keyColumns, "t2", inputMap);
					if (!ViewUtil.isNuLLStr(keyWhereSql))
					{
						sql.append("and ");
						sql.append(keyWhereSql + " ");
					}

					sql.append(")");

					List<Map> childdatas = findData(childtableCode,
							DicColumnDto.create(childDicColumns), sql
									.toString(), 0, 0);
					if (null != childdatas && childdatas.size() > 0)
					{
						if (deletechilds)
						{
							// 递归删除
							deleteData(childtableCode, childdatas);
						} else
						{
							String msg = "删除"
									+ tableCode
									+ "表记录出错！因为"
									+ childtableCode
									+ "表"
									+ dicColumn.getDicColumnPK()
											.getColumncode()
									+ "字段中关联记录！请先删除关联记录！";
							logger.error(msg);
							throw new BusinessException(
									"data.delete.haschild.exception");
						}
					}
				}
			}
		}
		StringBuilder deleteSQL = new StringBuilder("delete t from ");
		deleteSQL.append(tableCode);
		deleteSQL.append(" t where ");

		for (Map inputMap : list)
		{
			for (String keyColumn : keyColumns)
			{
				if (ViewUtil.isNuLLValueInMap(inputMap, keyColumn))
				{
					throw new BusinessException(
							"data.input.donthaskeycolumn.exception");
				}
			}
			String keySql = getWhereSqlByKeycolumn(tableCode, keyColumns, "t",
					inputMap);
			deleteSQL.append("(");
			deleteSQL.append(keySql);
			deleteSQL.append(") or ");
		}
		deleteSQL.delete(deleteSQL.length() - 3, deleteSQL.length());
		String connectionBeanName = getDatabaseBeanName(tableCode);
		dynamicDBDaoImpl.execute(connectionBeanName, deleteSQL.toString());

		// 记录修改对象的信息进入缓存消息中
		List<Map<String, String>> cacheMessages = new ArrayList<Map<String, String>>();
		for (Map inputMap : list)
		{
			Map<String, String> cacheMessage = createCacheMessage(
					DataOperateMessageUtil.DELETE_ACTION_TYPE, tableCode,
					inputMap);
			cacheMessages.add(cacheMessage);
		}
		DataOperateMessageUtil.addDataOperateMessages(cacheMessages);
		logger.info("deleteData method run end.");
	}

	/**
	 * Description : 根据字段列表，创建字段等于值的sql字符串
	 * 
	 * @param alias
	 * @param dicColumns
	 * @param inputMap
	 * @return
	 * 
	 */
	@SuppressWarnings("unchecked")
	private String buildColumnEqValueSqlByDicColumns(String alias,
			String joinSeq, List<DicColumn> dicColumns, Map inputMap)
	{
		StringBuilder columnEqValueSqls = new StringBuilder();
		for (DicColumn dicColumn : dicColumns)
		{
			String columnEqValueSql = this.buildColumnEqValueSqlByDicColumn(
					alias, dicColumn.getDicColumnPK().getColumncode(), "=",
					dicColumn, inputMap);
			if (!ViewUtil.isNuLLStr(columnEqValueSql))
			{
				columnEqValueSqls.append(columnEqValueSql);
				columnEqValueSqls.append(" ");
				columnEqValueSqls.append(joinSeq);
				columnEqValueSqls.append(" ");
			}
		}
		if (columnEqValueSqls.length() > 0)
		{
			int len = joinSeq.length() + 1;
			columnEqValueSqls.delete(columnEqValueSqls.length() - len,
					columnEqValueSqls.length());
		}
		return columnEqValueSqls.toString();
	}

	/**
	 * Description : 根据字段，创建字段等于值的sql字符串
	 * 
	 * @param alias
	 * @param joinSeq
	 * @param dicColumn
	 * @param inputMap
	 * @return
	 * 
	 */
	@SuppressWarnings("unchecked")
	private String buildColumnEqValueSqlByDicColumn(String alias,
			String columncode, String joinSeq, DicColumn dicColumn, Map inputMap)
	{
		StringBuilder result = new StringBuilder();
		String valueColumncode = dicColumn.getDicColumnPK().getColumncode();
		if (inputMap.containsKey(valueColumncode))
		{
			Object value = inputMap.get(valueColumncode);
			if (null != value)
			{
				String datatype = dicColumn.getDatatype();
				if ("N".equals(datatype))
				{
					if (ViewUtil.isNum(value.toString()))
					{
						result.append(alias);
						result.append(".");
						result.append(columncode);
						result.append(joinSeq);
						result.append(value);
					} else
					{
						return "";
					}
				} else if ("L".equals(datatype))
				{
					if (ViewUtil.isBoolean(value.toString()))
					{
						result.append(alias);
						result.append(".");
						result.append(columncode);
						result.append(joinSeq);
						result.append(value);
					} else
					{
						return "";
					}
				} else if ("D".equals(datatype))
				{
					if (ViewUtil.isDate(value.toString()))
					{
						result.append(alias);
						result.append(".");
						result.append(columncode);
						result.append(joinSeq);
						result.append("'" + value + "'");
					} else
					{
						return "";
					}

				} else if ("T".equals(datatype))
				{
					if (ViewUtil.isTime(value.toString()))
					{
						result.append(alias);
						result.append(".");
						result.append(columncode);
						result.append(joinSeq);
						result.append("'" + value + "'");
					} else
					{
						return "";
					}
				} else
				{
					value = ViewUtil.dealMysqlSpecialChar(value.toString());
					result.append(alias);
					result.append(".");
					result.append(columncode);
					result.append(joinSeq);
					result.append("'" + value + "'");
				}
			}
		}
		return result.toString();
	}

	/**
	 * Description : 检查表定义中是否有字段定义
	 * 
	 * @param tablecode
	 * @throws BusinessException
	 * 
	 */
	private void checkDicTableHasDicColumns(String tablecode)
			throws BusinessException
	{
		List<DicColumn> dicColumns = findDicColumnsByTablecode(tablecode);
		if (null == dicColumns || dicColumns.size() == 0)
		{
			logger.error(tablecode + "表没有配置字段!");
			throw new BusinessException(
					"table.config.notexists.column.exception");
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.adams.custom.page.core.service.impl.DicTableService#getDataByKey
	 * (java.lang.String, java.util.Map)
	 */
	@SuppressWarnings("unchecked")
	public Map getDataByKey(String tablecode, Map inputMap)
			throws BusinessException
	{
		logger.info("getDataByKey method run begin.");
		DicTable dicTable = dicTableDaoImpl.getDicTable(tablecode);
		checkDicTableKeycolumns(tablecode, inputMap);
		List<String> keycolumns = dicTable.getKeycolumnlist();

		checkDicTableHasDicColumns(tablecode);
		List<DicColumn> dicColumns = findDBDicColumnsByTablecode(tablecode);
		String alias = TABLE_ALIAS + 0;
		String whereSql = getWhereSqlByKeycolumn(tablecode, keycolumns, alias,
				inputMap);
		String sql = buildSearchSql(dicTable, dicColumns, alias, whereSql
				.toString(), null);
		List<Map> viewGridDatasList = findData(tablecode, DicColumnDto
				.create(dicColumns), sql, 0, 0);
		if (null == viewGridDatasList || viewGridDatasList.size() == 0)
		{
			return null;
		}
		Map result = viewGridDatasList.get(0);
		logger.info("getDataByKey method run end.");
		return result;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @seecom.adams.custom.page.core.service.impl.DicTableService#
	 * findDBDicColumnsByTablecode(java.lang.String)
	 */
	public List<DicColumn> findDBDicColumnsByTablecode(String tablecode)
	{
		logger.info("findDBDicColumnsByTablecode method run begin.");
		List<DicColumn> dicColumns = findDicColumnsByTablecode(tablecode);

		for (Iterator<DicColumn> it = dicColumns.iterator(); it.hasNext();)
		{
			DicColumn dicColumn = it.next();
			if (!dicColumn.getDbcolumn())
			{
				it.remove();
			}
		}
		logger.info("findDBDicColumnsByTablecode method run end.");
		return dicColumns;
	}

	/**
	 * Description : 得到where条件根据关键字段
	 * 
	 * @param tablecode
	 * @param keycolumns
	 * @param alias
	 * @param inputMap
	 * @return
	 * @throws BusinessException
	 * 
	 */
	@SuppressWarnings("unchecked")
	private String getWhereSqlByKeycolumn(String tablecode,
			List<String> keycolumns, String alias, Map inputMap)
			throws BusinessException
	{
		List<DicColumn> dicColumns = new ArrayList<DicColumn>();
		for (String keycolumn : keycolumns)
		{
			DicColumn dicColumn = getDicColumn(tablecode, keycolumn);
			dicColumns.add(dicColumn);
		}
		String columnEqValueSql = buildColumnEqValueSqlByDicColumns(alias,
				"and", dicColumns, inputMap);
		return columnEqValueSql;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @seecom.adams.custom.page.core.service.impl.DicTableService#
	 * checkDicTableKeycolumns(java.lang.String, java.util.Map)
	 */
	@SuppressWarnings("unchecked")
	public void checkDicTableKeycolumns(String tablecode, Map inputMap)
			throws BusinessException
	{
		logger.info("checkDicTableKeycolumns method run begin.");
		DicTable dicTable = dicTableDaoImpl.getDicTable(tablecode);
		List<String> keycolumns = dicTable.getKeycolumnlist();
		if (null == keycolumns || keycolumns.size() == 0)
		{
			logger.error(tablecode + "表没有配置关键字段!");
			throw new BusinessException("table.no.has.keycolumn.exception");
		}
		for (String keycolumn : keycolumns)
		{
			DicColumn dicColumn = getDicColumn(tablecode, keycolumn);
			String datatype = dicColumn.getDatatype();
			if (!("N".equals(datatype) || "S".equals(datatype)))
			{
				logger.error("关键字段配置错误，关键字段只能是数值或者字符串！table:" + tablecode
						+ " keycolumn:" + keycolumn);
				throw new BusinessException("table.keycolumn.exception");
			}
			if (null != inputMap)
			{
				if (!inputMap.containsKey(keycolumn))
				{
					logger.error(keycolumn + "字段必须有值！");
					throw new BusinessException(
							"data.input.nohas.keycolumn.exception");
				}
				Object value = inputMap.get(keycolumn);
				if (null == value)
				{
					logger.error(keycolumn + "字段必须有值！");
					throw new BusinessException(
							"data.input.nohas.keycolumn.exception");
				}
			}
		}
		logger.info("checkDicTableKeycolumns method run end.");
	}

	/**
	 * Description : 检查数据中是否有相同的编码
	 * 
	 * @param tablecode
	 * @param inputMap
	 * @throws BusinessException
	 * 
	 */
	@SuppressWarnings("unchecked")
	public void checkDataByCodeColumn(String tablecode, Map inputMap)
			throws BusinessException
	{
		logger.info("checkDataByCodeColumn method run begin.");
		String alias = "t";
		DicTable dicTable = dicTableDaoImpl.getDicTable(tablecode);
		String columncode = dicTable.getCodecolumn();

		if (ViewUtil.isNuLLStr(columncode))
		{
			return;
		}
		if (!inputMap.containsKey(columncode))
		{
			logger.error(columncode + "字段必须有值！");
			throw new BusinessException("data.input.nohas.codecolumn.exception");
		} else
		{
			Object value = inputMap.get(columncode);
			if (null == value || "".equals(value.toString().trim()))
			{
				logger.error(columncode + "字段必须有值！");
				throw new BusinessException(
						"data.input.nohas.codecolumn.exception");
			}
		}

		StringBuilder whereSql = new StringBuilder("");
		if (!ViewUtil.isNuLLStr(columncode))
		{
			DicColumn dicColumn = getDicColumn(tablecode, columncode);
			String columnEqValueSql = this.buildColumnEqValueSqlByDicColumn(
					alias, dicColumn.getDicColumnPK().getColumncode(), "=",
					dicColumn, inputMap);
			if (!ViewUtil.isNuLLStr(columnEqValueSql))
			{
				whereSql.append(columnEqValueSql);
				whereSql.append(" and ");
			}
			List<String> keycolumns = dicTable.getKeycolumnlist();
			if (null != keycolumns && keycolumns.size() > 0)
			{
				for (String keycolumn : keycolumns)
				{
					if (!inputMap.containsKey(keycolumn))
					{
						continue;
					}
					Object value = inputMap.get(keycolumn);
					if (null == value || "".equals(value))
					{
						continue;
					}
					dicColumn = getDicColumn(tablecode, keycolumn);
					columnEqValueSql = this.buildColumnEqValueSqlByDicColumn(
							"t", dicColumn.getDicColumnPK().getColumncode(),
							"!=", dicColumn, inputMap);
					if (!ViewUtil.isNuLLStr(columnEqValueSql))
					{
						whereSql.append(columnEqValueSql);
						whereSql.append(" and ");
					}
				}
			}

			if (whereSql.length() > 4)
			{
				whereSql.delete(whereSql.length() - 4, whereSql.length());
			}

			int totalcount = getCount(tablecode, alias, whereSql.toString());
			if (totalcount > 0)
			{
				throw new BusinessException("inputdata.code.exists.exception");
			}
		}
		logger.info("checkDataByCodeColumn method run end.");
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @seecom.adams.custom.page.core.service.DicTableService#
	 * synchronizationCache()
	 */
	@Override
	public void synchronizationCache() throws BusinessException
	{
		logger.info("synchronizationCache method run begin.");
		// TODO Auto-generated method stub
		dicDatabaseDaoImpl.synchronizationCache();
		dicTableDaoImpl.synchronizationCache();
		dicColumnDaoImpl.synchronizationCache();
		dicElementDaoImpl.synchronizationCache();
		logger.info("synchronizationCache method run end.");
	}

	/**
	 * Description : 创建缓存消息对象
	 * 
	 * @param actiontype
	 * @param tablecode
	 * @param inputMap
	 * @return
	 * @throws BusinessException
	 * 
	 */
	@SuppressWarnings("unchecked")
	private Map<String, String> createCacheMessage(String actiontype,
			String tablecode, Map inputMap) throws BusinessException
	{
		Map<String, String> cacheMessage = new HashMap<String, String>();
		cacheMessage.put(DataOperateMessageUtil.ACTION_TYPE, actiontype);
		cacheMessage.put(DataOperateMessageUtil.TABLE_NAME, tablecode);
		DicTable dicTable = getDicTable(tablecode);
		List<String> keycolumns = dicTable.getKeycolumnlist();
		for (String keycolumn : keycolumns)
		{
			if (ViewUtil.isNuLLValueInMap(inputMap, keycolumn))
			{
				continue;
			}
			Object value = inputMap.get(keycolumn);
			if (null != value)
			{
				cacheMessage.put(keycolumn, value.toString());
			}
		}
		return cacheMessage;
	}

	@Override
	public int updateData(String tablecode, String sql)
			throws BusinessException
	{

		String connectionBeanName = getDatabaseBeanName(tablecode);
		int result = dynamicDBDaoImpl.execute(connectionBeanName, sql);
		// 记录修改对象的信息进入缓存消息中
		Map<String, String> cacheMessage = createCacheMessage(
				DataOperateMessageUtil.UPDATE_ACTION_TYPE, tablecode,
				new HashMap());
		DataOperateMessageUtil.addDataOperateMessage(cacheMessage);
		return result;
	}

}
